package com.jonsnowsword.wifiassistant;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.jonsnowsword.wifiassistant.GoogleAnalyticsApplication.TrackerName;

public class CodeManageActivity extends Activity{
	private WifiPassword wifiPassword;
	private List<Wifi> wifiList;
	private InterstitialAd interstitialAd;
	private static boolean isExit;
	private static boolean isLoad;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.code_manage);

		adinit();
        try {
            Init();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	public void Init() throws Exception {
		isExit = false;
		List<Wifi> wifiInfos = new ArrayList<Wifi>();
		wifiPassword = new WifiPassword();
		wifiInfos = wifiPassword.Read();
        ListView wifiInfosView=(ListView)findViewById(R.id.listView2);
        wifiList = FileUtil.getwifiInfosList();
        wifiList = combine(wifiList,wifiInfos);
        WifiAdapter ad = new WifiAdapter(this,wifiList);
        wifiInfosView.setAdapter(ad);
        wifiInfosView.setOnItemClickListener(new OnItemClickListenerImpl(CodeManageActivity.this));
    }
     
	
	@Override
	protected void onResume() {
		// TODO 自动生成的方法存根
		sendGoogleAnalyticsView();
		super.onResume();
	}



	Tracker mTracker;

	public void sendGoogleAnalyticsView()
	{
		// Get tracker.
		mTracker = ((GoogleAnalyticsApplication) getApplication()).getTracker(TrackerName.GLOBAL_TRACKER);

		// Set screen name.
		// Where path is a String representing the screen name.
		mTracker.setScreenName("CodeManageActivity");

		// Send a screen view.
		mTracker.send(new HitBuilders.AppViewBuilder().build());
	}
	
	
    private List<Wifi> combine(List<Wifi> wifiList, List<Wifi> wifiInfos) {
		// TODO Auto-generated method stub
		if(wifiList.size()==0)
		{
			if(wifiInfos.size()==0)
			{
				return wifiList;
			}
			else
			{
				return wifiInfos;
			}
		}
		else
		{
			if(wifiInfos.size()==0)
			{
				return wifiList;
			}
			else
			{
				for(int i=0;i<wifiInfos.size();i++)
				{
					for(int j=0;j<wifiList.size();j++)
					{
						if(wifiInfos.get(i).getSsid().equals(wifiList.get(j).getSsid()))
						{
							break;
						}
						if(j==wifiList.size()-1)
						{
							Wifi wifiInfo=new Wifi();
							wifiInfo.Ssid=wifiInfos.get(i).getSsid();
							wifiInfo.Password=wifiInfos.get(i).getPassword();
							wifiInfo.Capabilities=wifiInfos.get(i).getCapabilities();
							wifiInfo.IsUserRecord=0;
							wifiList.add(wifiInfo);
						}
					}
						
				}
				return wifiList;
			}
		}
	}





	public class WifiAdapter extends BaseAdapter{
 
    	LayoutInflater inflater;  
        List<Wifi> wifiInfos =null;
         
        public WifiAdapter(Context context,List<Wifi> wifiInfos){
            // TODO Auto-generated constructor stub  
        	this.inflater = LayoutInflater.from(context); 
            this.wifiInfos =wifiInfos;
        }
         
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return wifiInfos.size();
        }
 
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return wifiInfos.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
        	
            View view = inflater.inflate(R.layout.item_wifi_code_list, null);  

            Wifi wifi = wifiInfos.get(position);  
            TextView textView1 = (TextView) view.findViewById(R.id.wifiNameView2);  
            textView1.setText(wifi.getSsid());  

            TextView textView2 = (TextView) view.findViewById(R.id.wifiCodeView);  
            textView2.setText("password: "+wifi.getPassword());  
            
            TextView textView3 = (TextView) view.findViewById(R.id.wifiCapabilitiesView2);  
            textView3.setText(wifi.getCapabilities()); 
            
            ImageView imageView = (ImageView) view.findViewById(R.id.WifiView2);  
            if(!(wifi.getPassword().equals("")||wifi.getPassword().equals("empty")))
            {
            	imageView.setImageResource(R.drawable.wifi_lock);
            }	           
            TextView textView4 = (TextView) view.findViewById(R.id.addByUser);  
            if(wifi.IsUserRecord==0)
            {
            	textView4.setVisibility(View.GONE);
            }

            
            return view;  
        }
         
    }
    

	private class OnItemClickListenerImpl implements OnItemClickListener {

		private Context context;

		
		public OnItemClickListenerImpl(Context context)
		{
			this.context=context;
		}
		
		
		@SuppressWarnings({ "deprecation" })
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,  long id) 
		{
			final Wifi wifi=(Wifi) arg0.getItemAtPosition(position);
			if(wifi.IsUserRecord==0)
			{
				new AlertDialog.Builder(CodeManageActivity.this)  
				.setTitle(wifi.getSsid())  
				.setItems(new String[] {"Share","Copy the password","Edit"}, new DialogInterface.OnClickListener() {
					
					@SuppressLint("NewApi")
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
						
						if(which==0)
						{
			                Intent intent=new Intent(Intent.ACTION_SEND);   
			                intent.setType("image/*");   
			                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");   
			                intent.putExtra(Intent.EXTRA_TEXT, wifi.getSsid()+":"+wifi.getPassword());   
			                
			                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
			                startActivity(Intent.createChooser(intent, getTitle()));  
						}
						else if(which==1)
						{
							int sdkVer = android.os.Build.VERSION.SDK_INT;
							 
							if(sdkVer < android.os.Build.VERSION_CODES.HONEYCOMB) 
							{
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								clipboard.setText(wifi.getPassword());
							} 
							                
							else 
							{
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
								android.content.ClipData clip = android.content.ClipData.newPlainText("Password",wifi.getPassword());
								clipboard.setPrimaryClip(clip);
							}
						}
						else
						{
							final EditText  editText=new EditText(context);
							editText.setInputType(0x81);
							new AlertDialog.Builder(CodeManageActivity.this) 
					          .setTitle( wifi.getSsid())
					          .setMessage("Please change your password")
					          .setView(editText)
					          .setNegativeButton("No", null) 
					          .setPositiveButton("Yes", new OnClickListener() 
					          {
					        	  	@Override
									public void onClick(DialogInterface dialog, int which) 
									{	
					        	  		FileUtil.rewrite(wifi.getSsid());
					        	  		String b=editText.getText().toString();
					        	  		if(b.equals(""))
					        	  		{
					        	  			b="empty";
					        	  		}
					        	  		FileUtil.write(wifi.getSsid(), b,wifi.getCapabilities());
					        			try {
											Init();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}				
					          }).show();
						}
					}
				})  
				.setNegativeButton("Yes", null)  
				.show();
			}
			else
			{
				new AlertDialog.Builder(CodeManageActivity.this)  
				.setTitle(wifi.getSsid())  
				.setItems(new String[] {"Share","Copy the password","Edit","Delete"}, new DialogInterface.OnClickListener() {
					
					@SuppressLint("NewApi")
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
						
						if(which==0)
						{
			                Intent intent=new Intent(Intent.ACTION_SEND);   
			                intent.setType("image/*");   
			                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");   
			                intent.putExtra(Intent.EXTRA_TEXT, wifi.getSsid()+":"+wifi.getPassword());   
			                
			                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
			                startActivity(Intent.createChooser(intent, getTitle()));  
						}
						else if(which==1)
						{
							int sdkVer = android.os.Build.VERSION.SDK_INT;
							 
							if(sdkVer < android.os.Build.VERSION_CODES.HONEYCOMB) 
							{
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								clipboard.setText(wifi.getPassword());
							} 
							                
							else 
							{
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
								android.content.ClipData clip = android.content.ClipData.newPlainText("Password",wifi.getPassword());
								clipboard.setPrimaryClip(clip);
							}
						}
						else if(which==2)
						{
							final EditText  editText=new EditText(context);
							editText.setInputType(0x81);
							new AlertDialog.Builder(CodeManageActivity.this) 
					          .setTitle( wifi.getSsid())
					          .setMessage("Please change your password")
					          .setView(editText)
					          .setNegativeButton("No", null) 
					          .setPositiveButton("Yes", new OnClickListener() 
					          {
					        	  	@Override
									public void onClick(DialogInterface dialog, int which) 
									{	
					        	  		FileUtil.rewrite(wifi.getSsid());
					        	  		String b=editText.getText().toString();
					        	  		if(b.equals(""))
					        	  		{
					        	  			b="empty";
					        	  		}
					        	  		FileUtil.write(wifi.getSsid(), b,wifi.getCapabilities());
					        			try {
											Init();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}				
					          }).show();
						}
						else if(which==3)
						{
							new AlertDialog.Builder(CodeManageActivity.this) 
					          .setTitle( wifi.getSsid())
					          .setMessage("Confirmed to delete the record?")
					          .setNegativeButton("No", null) 
					          .setPositiveButton("Yes", new OnClickListener() 
					          {
					        	  	@Override
									public void onClick(DialogInterface dialog, int which) 
									{	
					        	  		FileUtil.rewrite(wifi.getSsid());
					        			try {
											Init();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}				
					          }).show();
						}
					}
				})  
				.setNegativeButton("Yes", null)  
				.show();
			}
			
			
			

		}
	
	}
	public void wifiConnect(View view)
	{
		Intent intent=new Intent(CodeManageActivity.this,WifiConnectActivity.class);
		startActivity(intent);
		finish();
	}
	
	public void codeManage(View view)
	{
		Intent intent=new Intent(CodeManageActivity.this,CodeManageActivity.class);
		startActivity(intent);
		finish();
	}
	
	public void addRecord(View view)
	{
		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
		List<ScanResult> availableList = wifiManager.getScanResults();
		List<ScanResult> list = new ArrayList<ScanResult>();
		if(availableList==null)
		{
			Intent intent=new Intent();
			intent.setClass(this, AddRecordActivity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelableArrayList("list",(ArrayList<? extends Parcelable>) list);
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
		}
		else
		{
			if(availableList.size()!=0)
			{
				if(wifiList.size()==0)
					list=availableList;
				else
				{
					for(int i=0;i<availableList.size();i++)
					{
						for(int j=0;j<wifiList.size();j++)
						{
							if(availableList.get(i).SSID.equals(wifiList.get(j).getSsid()))
								break;
							if(j==wifiList.size()-1)
								list.add(availableList.get(i));
						}					
					}
				}	
			}


			Intent intent=new Intent();
			intent.setClass(this, AddRecordActivity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelableArrayList("list",(ArrayList<? extends Parcelable>) list);
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
		}
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			Init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onBackPressed()
	{
		if(isLoad==false)
			finish();
		else{
			showInterstitial();
			exit();
		}

		
		
	}


	 private void exit() {
	        if (!isExit) {
	            isExit = true;
	        } else {
	            finish();
	        }
	    }
	
	private void adinit() {
		// TODO Auto-generated method stub
		
		
	    AdView adView = (AdView) this.findViewById(R.id.adView2);
	    AdRequest adRequestBanner = new AdRequest.Builder().build();
	    adView.loadAd(adRequestBanner);
	    
	    isLoad=false;
	    interstitialAd = new InterstitialAd(this);
	    interstitialAd.setAdUnitId("ca-app-pub-6475651336232944/8988360917");
	    interstitialAd.setAdListener(new AdListener() {
	        @Override
	        public void onAdLoaded() {

	        	isLoad=true;
	        }


	      });

	    AdRequest adRequestInterstitial = new AdRequest.Builder().build();
	    interstitialAd.loadAd(adRequestInterstitial);
	}
	
	
	  public void showInterstitial() {
		    // Disable the show button until another interstitial is loaded.

		    if (interstitialAd.isLoaded()) {
		      interstitialAd.show();
		    } 
		  }
	
}
